from conan import ConanFile
from conan.tools.files import (
    apply_conandata_patches,
    copy,
    get,
    chdir,
    replace_in_file
)
from conan.tools.gnu import Autotools, AutotoolsToolchain, AutotoolsDeps
from conan.tools.layout import basic_layout
import os
import subprocess

required_conan_version = ">=1.54.0"

class LibartConan(ConanFile):
    name = "libart"
    description = "Adaptive Radix Trees implemented in C"
    url = "https://github.com/conan-io/conan-center-index"
    homepage = "https://github.com/armon/libart"
    package_type = "library"
    settings = "os", "arch", "compiler", "build_type"
    options = {
        "shared": [True, False],
        "fPIC": [True, False],
    }
    default_options = {
        "shared": True,
        "fPIC": True,
    }

    @property
    def _settings_build(self):
        return getattr(self, "settings_build", self.settings)

    def configure(self):
        if self.options.shared:
            self.options.rm_safe("fPIC")

    def layout(self):
        basic_layout(self, src_folder="src")
        
    def build_requirements(self):
        if self._settings_build.os == "Windows":
            self.win_bash = True
            if not self.conf.get("tools.microsoft.bash:path", check_type=str):
                self.tool_requires("msys2/cci.latest")

    def source(self):
        get(self, **self.conan_data["sources"][self.version], strip_root=True)

    def generate(self):
        tc = AutotoolsToolchain(self)

        if "arm" in self.settings.arch and self.settings.os == "OHOS":
            tc.configure_args.append("--host=arm-linux")

        tc.generate()
        deps = AutotoolsDeps(self)
        deps.generate()

    def chmod_file(self):
        chmod_cmd = ['chmod', '-R', '777']
        chmod_cmd.append(os.path.join(self.source_folder, "deps", "check-0.9.8", "configure"))
        subprocess.run(chmod_cmd, stdout=subprocess.PIPE)
    
    def _patch_sources(self):
        apply_conandata_patches(self)
        replace_in_file(self, os.path.join(self.source_folder, "deps", "check-0.9.8", "configure"),
            "cd $srcdir && pwd", "pwd")
        replace_in_file(self, os.path.join(self.source_folder, "deps", "check-0.9.8", "tests", "check_check.h"),
            "int sub_nfailed", "static int sub_nfailed")
        replace_in_file(self, os.path.join(self.source_folder, "deps", "check-0.9.8", "tests", "check_check.h"),
            "int sub_ntests", "static int sub_ntests")


    def build(self):
        if self._settings_build.os == "Linux":
            self.chmod_file()

        print("build_folder")
        print(self.build_folder)

        print("source_folder")
        print(self.source_folder)

        print("package_folder")
        print(self.package_folder)
        self._patch_sources()
        vars = self.buildenv.vars(self)
        args_make = [
            "PREFIX={}".format(self.package_folder),
            "CC=\"{}\"".format(vars.get("CC")),
            "LD=\"{}\"".format(vars.get("CC")),
            "AR=\"{}\"".format(vars.get("AR")),
            "SHLINKFLAGS={}".format("-shared" if self.options.shared else ""),
            "fPIC={}".format("" if self.options.shared else "-fPIC"),
            "SUF={}".format(".so" if self.options.shared else ".a"),
        ]

        autotools = Autotools(self)
        autotools.configure(build_script_folder=os.path.join(self.source_folder, "deps", "check-0.9.8"))
        autotools.make()

        with chdir(self, self.source_folder):
            autotools = Autotools(self)
            autotools.make(args=args_make)

    def package(self):
        # copy check libs
        copy(self, "LICENSE", self.source_folder, os.path.join(self.package_folder, "licenses"))

        lib_suffix = "lib*.so*" if self.options.shared else "lib*.a"
        copy(self, lib_suffix, os.path.join(self.build_folder, "src", ".libs"), os.path.join(self.package_folder, "lib"))
        copy(self, lib_suffix, os.path.join(self.source_folder, "src"), os.path.join(self.package_folder, "lib"))
        
        copy(self, "*.h",  os.path.join(self.build_folder, "src"), os.path.join(self.package_folder, "include"))
        copy(self, "*.h",  os.path.join(self.source_folder, "src"), os.path.join(self.package_folder, "include"))

    def package_info(self):
        self.cpp_info.set_property("cmake_file_name", "Art")

        self.cpp_info.components["art"].set_property("cmake_target_name", "Art::Art")
        self.cpp_info.components["art"].libs = ["art"]

        self.cpp_info.components["check"].set_property("cmake_target_name", "Art::check")
        self.cpp_info.components["check"].libs = ["check"]

        # TODO: to remove in conan v2
        self.cpp_info.names["cmake_find_package"] = "Art"
        self.cpp_info.names["cmake_find_package_multi"] = "Art"
        self.env_info.PATH.append(os.path.join(self.package_folder, "bin"))